/*
 * axios全局配置
 */
import axios, { AxiosRequestConfig } from 'axios'
import { message } from 'antd'
import { store } from '@/store'
import qs from 'qs'
import { changeRouteList, changeMenuList, changeUserRouteList, changeDictData } from '@/store/reducers/login'
import { changeUserInfoAction } from '@/store/reducers/user'
import { Token_Key } from '@/config'
const instance = axios.create({
  timeout: 15000,
})
// 是否正在刷新的标记
let isRefreshing = false
const removeLoginStatus = async () => {
  message.warning('登录已过期，请重新登录')
  window.localStorage.setItem(Token_Key, '')
  await store.dispatch(changeUserInfoAction({}))
  await store.dispatch(changeMenuList([]))
  await store.dispatch(changeRouteList([]))
  await store.dispatch(changeUserRouteList([]))
  await store.dispatch(changeDictData({}))
  window.localStorage.removeItem('persist:qsfpc')
  isRefreshing = true
}
//配置请求拦截器
instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    if (!config.headers) {
      config.headers = {}
    }
    config.headers['Access-Token'] = window.localStorage.getItem(Token_Key) || ''
    config.headers['User-Id'] = store.getState().user.user_info.userId || ''
    config.headers['Application-Id'] = store.getState().user.user_info.applicationId || ''
    config.headers['Org-Id'] = store.getState().user.user_info.orgId || ''
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

//配置响应拦截器
instance.interceptors.response.use(
  (response) => {
    isRefreshing = false
    if (response?.data?.code === 200 || (response?.data?.code + '').slice(0, 4) === '8200') {
      return response?.data
    } else if (Object.prototype.toString.call(response.data) === '[object Blob]') {
      return response
    } else {
      message.error(response?.data?.msg || '系统版本更新中，请稍后重试！')
      return Promise.reject(response?.data)
    }
  },
  async (error) => {
    if (error?.code === 'ECONNABORTED' && error?.message?.includes('timeout')) {
      message.error('请求超时，请稍后再试！')
    } else if (error?.response?.status === 401) {
      if (isRefreshing) {
        return Promise.reject(error)
      }
      removeLoginStatus()
      return Promise.reject(error)
    } else {
      message.error('系统版本更新中，请稍后重试！')
    }
    return Promise.reject(error)
  },
)

export const getRequest = <T>(url = '', data = {}) => {
  if (qs.stringify(data)) {
    url += url.includes('?') ? '&' + qs.stringify(data) : '?' + qs.stringify(data)
  }
  return instance.get(url) as Promise<IResponseData<T>>
}
export const getRequestInfo = <T>(url = '', data = {}) => {
  if (qs.stringify(data)) {
    url += url.includes('?') ? '&' + qs.stringify(data) : '?' + qs.stringify(data)
  }
  return instance.get(url) as Promise<IResponsePost<T>>
}
export const getRequestById = <T>(url = '', data: string | number) => {
  return instance.get(url + data) as Promise<IResponseData<T>>
}
export const delRequestPost = <T>(url = '', data = {}) => {
  if (qs.stringify(data)) {
    url += url.includes('?') ? '&' + qs.stringify(data) : '?' + qs.stringify(data)
  }
  return instance.post(url) as Promise<IResponseData<T>>
}
export const postRequestList = <T>(url = '', data = {}, obj = {}) => {
  return instance.post(url, data, obj) as Promise<IResponseList<T>>
}
export const postRequest = <T>(url = '', data = {}) => {
  return instance.post(url, data) as Promise<IResponsePost<T>>
}
export const postRequestData = <T>(url = '', data = {}, obj = {}) => {
  //过滤对象中值为''
  const filterData = Object.fromEntries(Object.entries(data)?.filter(([_, val]) => val !== ''))
  return instance.post(url, filterData, obj) as Promise<IResponseData<T>>
}
export const postRequestJson = <T>(url = '', data: any, obj = {}) => {
  return instance.post(url, data, { ...obj, headers: { 'Content-Type': 'application/json' } }) as Promise<
    IResponsePost<T>
  >
}
export const importFile = async <T>(url = '', file: any, extraParams?: any) => {
  // if (file?.size > 1024 * 1024 * 10) {
  //   message.error('文件大小不能超过10MB！')
  //   return Promise.reject(false)
  // }
  const formData = new FormData()
  formData.append('file', file)
  if (extraParams && Object.keys(extraParams).length > 0) {
    Object.keys(extraParams).forEach((key) => {
      formData.append(key, extraParams[key])
    })
  }
  return instance.post(url, formData, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }) as Promise<
    IResponsePost<T>
  >
}

export const uploadFile = async <T>(file: any) => {
  const formData = new FormData()
  formData.append('file', file)
  return instance.post('/api/sop/sop/file/upload', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  }) as Promise<IResponsePost<T>>
}
